﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using blackhouse.BlackApart.Web;
using System.IO;
using blackhouse.BlackApart.Business.Reservations;
using blackhouse.BlackApart.Business.Apartments;
using System.Globalization;
using blackhouse.JavaScript.JQuery;
using blackhouse.Web;
using blackhouse.BlackApart.Business;

namespace blackhouse.Aparts.Web.Pages {
	public partial class ProgressReservation : NonCmsBasePage {

		#region Fields

		private string reservationId;
		private int variantId;
		private int groupId;
		private SearchReservationPerRequest requestData;
		private Variant selectedVariant;
		private double priceForOne = 0;
		private double priceForAll = 0;
		private double priceWithoutRabatForAll = 0;
		private bool showRabatInformation = false;
		private int lengthOfStayInDays = 0;

		#endregion

		#region Event Handlers

		protected override void OnPreInit(EventArgs e) {
			this.AllowSkinOverride = true;
			HttpContext.Current.Items.Add("skin", "blackhouse");

			base.OnPreInit(e);
		}

		protected override void OnInit(EventArgs e) {
			base.OnInit(e);

			this.ReadParameters();
			this.CheckNeededSearch();
			this.SetInstance();
		}

		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);

			this.PopulateControls();
			this.AddJavaScripts();
			this.SetPageSeo();
		}

		#endregion

		#region Methods

		private void SetPageSeo() {
			PageProvider seo = PageProvider.Instance();
			seo.SetPageTitle(GetGlobalResourceObject("Aparts", "progressReservationTitle").ToString());
			seo.SetPageKeywords(GetGlobalResourceObject("Aparts", "progressReservationKeys").ToString());
			seo.SetPageDescription(GetGlobalResourceObject("Aparts", "reservationDescription").ToString());
		}

		private void AddJavaScripts() {
			JQueryLibraries jql = new JQueryLibraries();
			jql.IncludeJQueryFancybox();
			jql.IncludeJQueryUICulture(CultureInfo.CurrentCulture);
			jql.IncludeJQueryValidationEngine(CultureInfo.CurrentCulture);
			jql.IncludeJQueryForm();
			jql.IncludeFileBasedOnJQuery("blackhouse.Aparts.Web.Scripts.progressReservation.js,blackhouse.Aparts.Web");
		}

		private void ReadParameters() {
			this.reservationId = Request["reservation"];
			Int32.TryParse(Request["variant"], out this.variantId);
			if (!Int32.TryParse(Request["groupId"], out this.groupId))
				Int32.TryParse(Request["group"], out this.groupId);
		}

		private void CheckNeededSearch() {
			SearchState state = SearchState.GetFromContext();
			if (!state.IsSet) return;
			IUserReservation search = Factory.Instance().CreateUserReservation();
			search.SetDates(state.ArrivalDate, state.DepartureDate);
			search.SetForPeoples(state.PeopleCount);
			if (search is ConfiguredUserReservation) {
				(search as ConfiguredUserReservation).SetGroupFilter(this.groupId);
				Variant[] vs = search.Find();
				if (vs.Length > 0) {
					this.selectedVariant = vs.OrderBy(v => v.Price.GetPrice()).FirstOrDefault();
					this.requestData = new SearchReservationPerRequest(state.ArrivalDate, state.DepartureDate, state.PeopleCount);
					this.requestData.AddVariant(this.selectedVariant);
					this.requestData.Save(new DirectoryInfo(Server.MapPath("/SavedReservations")));
					Response.Redirect(UrlUtils.LocalizeUrl("/pages/progressreservation.aspx?reservation=" + this.requestData.Id + "&variant=" + this.requestData.GetIdForVariant(this.selectedVariant)));
				}
				else {
					Response.Redirect(UrlUtils.LocalizeUrl("/pages/apartments.aspx?search=" + state + "&mod=nofree"));
				}
			}
		}

		private void SetInstance() {
			int totNOfP = 0;

			if (!string.IsNullOrEmpty(this.reservationId)) {
				this.requestData = new SearchReservationPerRequest(this.reservationId, new DirectoryInfo(Server.MapPath("/SavedReservations")));
				this.selectedVariant = this.requestData.GetVariantFromId(this.variantId);
				this.lengthOfStayInDays = (int)Math.Ceiling((this.requestData.DepartureDate - this.requestData.ArrivalDate).TotalDays);
				totNOfP = this.requestData.NumberOfPeople;
			}

			if (this.selectedVariant != null) {
				this.priceForAll = this.selectedVariant.Price.GetPrice();
				this.priceWithoutRabatForAll = this.selectedVariant.Price.GetPriceWithoutRabat();
				if (this.priceForAll < this.priceWithoutRabatForAll)
					this.showRabatInformation = true;
				else {
					this.showRabatInformation = false;
					this.priceWithoutRabatForAll = this.priceForAll;
				}

				this.priceForOne = this.priceForAll / this.lengthOfStayInDays / totNOfP;
			}
		}

		private void PopulateControls() {
			if (this.requestData == null) {
				this.pnlProblemWithData.Visible = true;
				this.pnlProgressReservation.Visible = false;
				this.lnkToApartments.NavigateUrl = UrlUtils.LocalizeUrl("/apartamenty-lodz");
				return;
			}
			this.lblArrivalDate.Text = this.requestData.ArrivalDate.ToString("D");
			this.lblDepartureDate.Text = this.requestData.DepartureDate.ToString("D");
			this.lblLenfgthOfStay.Text = this.lengthOfStayInDays + " ";
			if (this.lengthOfStayInDays == 1)
				this.lblLenfgthOfStay.Text += "dzień";
			else
				this.lblLenfgthOfStay.Text += "dni";
			this.lblNumberOfPeople.Text = this.requestData.NumberOfPeople.ToString();
			this.PopulateSelectedApartment();

			this.cPriceOne.Value = this.priceForOne;
			this.cPriceTotal.Value = this.priceForAll;

			this.lblRabatInformation.Text = string.Format(GetGlobalResourceObject("Aparts", "progressRes7").ToString(), 100 * (1 - this.priceForAll / this.priceWithoutRabatForAll));
			this.lblRabatInformation.Visible = this.showRabatInformation;
			this.hidVariantId.Value = this.variantId.ToString();
			this.hidReservationId.Value = this.reservationId.ToString();
			this.PopulateArrivalTime();
		}

		private void PopulateSelectedApartment() {
			Dictionary<IApartment, int> d = new Dictionary<IApartment, int>();
            if (this.selectedVariant == null) {
                SiteUtils.RedirectToAccessDeniedPage();
                Response.End();
                return;
            }
			foreach (VariantItem vi in this.selectedVariant.Items) {
				if (!d.ContainsKey(vi.Apartment))
					d.Add(vi.Apartment, 0);
				d[vi.Apartment]++;
			}

			this.lblApartmentInfo.Visible = d.Count > 1;
			if (lblApartmentInfo.Visible)
				lblApartmentInfo.Text = GetGlobalResourceObject("Aparts", "progressRes4").ToString();

			List<string> s = new List<string>();
			foreach (KeyValuePair<IApartment, int> kvp in d) {
				string si = kvp.Value + " " + GetGlobalResourceObject("Aparts", "apartment");
				if (kvp.Value > 1) si += "y";
				si += " " + kvp.Key.Group.Name + " (" + string.Format(GetGlobalResourceObject("Aparts", "progressResPeople").ToString(), kvp.Key.NumberOfPeople) + ")";
				s.Add(si);
			}
			this.rptReservationApartments.DataSource = s;
			this.rptReservationApartments.DataBind();
		}

		private void PopulateArrivalTime() {
			this.ddlPersonHour.Items.Clear();
			TimeSpan ts = TimeSpan.FromHours(14);
			while (true) {
				string text = string.Format("{0:D2}:{1:D2}", ts.Hours, ts.Minutes);
				//if (ts.Days == 1)
				//    text += " następnego dnia";
				ListItem li = new ListItem(text, this.requestData.ArrivalDate.Date.Add(ts).ToString());
				this.ddlPersonHour.Items.Add(li);
				ts = ts.Add(TimeSpan.FromMinutes(30));
				if (ts.Days == 1 && ts.Hours == 14)
					break;
			}
		}

		#endregion

	}
}